﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EntityFrameworkETL.SaveBatchedChanges
{
    public interface ICommandCacheStructurer
    {
        IEnumerable<StructuredCommandCache> GeStructuredCommandCaches(IEnumerable<CommandCache> commandCaches);
    }

    public class CommandCacheStructurer : ICommandCacheStructurer
    {
        public IEnumerable<StructuredCommandCache> GeStructuredCommandCaches(IEnumerable<CommandCache> commandCaches)
        {
            var results = new List<StructuredCommandCache>();
            StructuredCommandCache PreviosDbCommandCacheItem = null;
            string TopLevelName = null;
            foreach (var commandCache in commandCaches)
            {
                var currentBatchedCommand = new StructuredCommandCache(commandCache);
                if (PreviosDbCommandCacheItem == null)
                {
                    PreviosDbCommandCacheItem = currentBatchedCommand;
                    TopLevelName = PreviosDbCommandCacheItem.CommandCache.TableName;
                }
                if (currentBatchedCommand.CommandCache.TableName == TopLevelName)
                {
                    results.Add(currentBatchedCommand);
                }
                else if (currentBatchedCommand.CommandCache.TableName == PreviosDbCommandCacheItem.CommandCache.TableName)
                {
                    PreviosDbCommandCacheItem.ParentCommand.ChildCommands.Add(currentBatchedCommand);
                    currentBatchedCommand.ParentCommand = PreviosDbCommandCacheItem.ParentCommand;
                }
                else if (PreviosDbCommandCacheItem.HasAncestor(currentBatchedCommand.CommandCache))
                {
                    var ancestor = PreviosDbCommandCacheItem.GetAncestor(currentBatchedCommand.CommandCache);
                    ancestor.ParentCommand.ChildCommands.Add(currentBatchedCommand);
                    currentBatchedCommand.ParentCommand = ancestor.ParentCommand;
                }
                else
                {
                    //new child
                    PreviosDbCommandCacheItem.ChildCommands.Add(currentBatchedCommand);
                    currentBatchedCommand.ParentCommand = PreviosDbCommandCacheItem;
                }

                PreviosDbCommandCacheItem = currentBatchedCommand;
            }
            
            return results;
        }
    }
}
